import { By, until, WebDriver } from "selenium-webdriver";
import { checkUiAutomator2Status, restartUiAutomator2, systemBack } from "../utils/systemBack.js";
import { clickCopyButton, clickShareButton, getClipboardLink, getElementValuesByPosition } from "../utils/clipboard.js";
import { extractDataFromPageSource } from "../utils/content.js";
import { AuthorProfile, NoteContent } from "../../lib/search.js";
import { ContentStateMachine } from "../../lib/statemachine.js";
import { DetectionEvent } from "../test/stateMachine.js";

let attempt = 1;

/**
 * Main_Function: 获取当前作者主页元素
 */
// 获取当前作者主页元素
export async function getAuthorProfile(contentMachine: ContentStateMachine, driver: WebDriver, maxRetries: number = 3): Promise<AuthorProfile> {
    
    const result: AuthorProfile = {
        redBookId: "",
        fansCount: 0,
        authorUrl: ""
    }

    try {
        await driver.sleep(3000)
        // await driver.sleep(2000);
        console.log("获取作者主页信息.....")
        console.log(`获取作者主页信${attempt}尝试.......`)
        // 尝试找到作者昵称元素
        const authorElement = await driver.findElement(
           By.id('com.xingin.xhs:id/nickNameTV'), 
        );
        
        if (authorElement) {
            // 点击作者昵称
            await authorElement.click();
        } 

        // 设置为 image_state 并获取指定位置的元素值 - "authorElement：小红书号，粉丝数，作者主页链接"
        contentMachine.dispatch(DetectionEvent.DETECT_IMAGE_TEXT);
        console.log('当前内容类型:', contentMachine.state);
        await driver.sleep(3000);
        const result = await getElementValuesByPosition(driver);
        console.log("authorElements: ",result)

        return result
    } catch(e) {

        try{
            await driver.sleep(3000)
            console.log("获取作者主页信息失败,是视频内容")
            console.log(`获取作者主页信${attempt}尝试.......`)
            
            const author = await driver.findElement(
                By.id('com.xingin.xhs:id/matrixNickNameView'), 
            );
            
            if (author) {
                await author.click();
            } 

            // 设置为 video_state
            contentMachine.dispatch(DetectionEvent.DETECT_VIDEO);
            console.log('当前内容类型:', contentMachine.state);
            const specificElements = await getElementValuesByPosition(driver);
            console.log("authorElements: ",specificElements)

            return specificElements
        }catch(e){
            // retry mechanism
            // if (maxRetries > 0) {
            //     attempt++;
            //     getAuthorProfile(contentMachine,driver, maxRetries - 1);
            // }else{
               
            // }
            console.error(`获取作者主页信息失败:`, e);
            return result
        }
    }

    return result
}

/**
 * 获取当前页面内容
 */
export async function getCurrentContent(contentMachine: ContentStateMachine,driver: WebDriver): Promise<NoteContent> {

    const result: NoteContent = {
        title: "",
        content: "",
        images: "",
        imagesCount: 0,
        link: "",
        likes: 0,
        collects: 0,
        comments: 0,
        noteType: '',
        publishTime: ''
    }

    try{
        const content = await extractDataFromPageSource(contentMachine,driver);
        return content;
    }catch(e){
        console.error(`获取当前页面内容失败:`, e);
        return result;
    }
}
    

